const {
  queryWorkOrders
} = require('../../api/workOrder')
const {
  APPROVEAL_STATUS,
  WORD_ORDER,
  SORT_ORDER
} = require('../../constant/index')

const {
  to,
  openLoading,
  closeLoading,
  routeWithToken
} = getApp()
Page({
  data: {
    loadingType: '',
    dataList: [],
    APPROVEAL_STATUS,
    WORD_ORDER,
    tabActive: WORD_ORDER.QUERY_BY_APPROVER_TO_DO,
    tabsList: [
      { name: '待审批', value: WORD_ORDER.QUERY_BY_APPROVER_TO_DO },
      { name: '全部', value: WORD_ORDER.QUERY_BY_APPROVER_ALL }
    ],
    pagination: {
      page: 1,
      limit: 10
    },
    total: 0
  },

  onLoad() {
    this.resetData()
    this.getQueryWorkOrders()
  },
  async getQueryWorkOrders(openL = true) {
    openL && openLoading()
    const [err, data] = await to(queryWorkOrders({
      queryPageCode: this.data.tabActive,
      orderByAscOrDesc: SORT_ORDER.DESC,
      notOrderByAbnormalAsc: true, // 非固定字段，有值了就代表不是按找异常优先排序
      ...this.data.pagination
    }));
    closeLoading()
    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })
      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }
      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },
  resetData() {
    this.setData({
      dataList: [],
      pagination: {
        page: 1,
        limit: 10
      },
      total: 0,
      loadingType: ''
    })
  },

  onReachBottom() {
    const {
      total,
      pagination,
      dataList
    } = this.data
    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getQueryWorkOrders(false)
    }
  },

  handleToRoute(event) {
    const item = event.detail
    routeWithToken(`/page-common/order-page/index?workOrderId=${item.workOrderId}`)
  },

  handleTabChange(event) {
    const code = event.detail.value;
    this.setData({
      tabActive: code
    })

    this.resetData()
    this.getQueryWorkOrders()
  },
})